﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Controllers
{
	using System.IO;
	using System.Web.Mvc;
	using Falcon.Core.Domain;
	using Falcon.Core.Domain.Services;
	using Falcon.Core.Extensions;

	public class AttachmentController : DefaultController
	{
		public AttachmentController(IAttachmentService attachmentService)
		{
			this.AttachmentService = attachmentService;
		}

		public IAttachmentService AttachmentService
		{
			get;
			private set;
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Detail(int id)
		{
			var attachment = AttachmentService.GetById(id);

			if (attachment == null)
			{
				return Error(Resources.Messages.AttachmentNotFound);
			}

			var path = attachment.FullPath.AsPath();
			var file = new FileInfo(path);

			if (!file.Exists)
			{
				return View(Views.Detail, attachment);
			}

			using (var stream = file.OpenRead())
			{
				return File(stream.ReadFully(), attachment.FileType);
			}
		}

		public ActionResult Image(int id, int width, int height)
		{
			var attachment = AttachmentService.GetById(id);

			if (attachment == null)
			{
				return Error(Resources.Messages.AttachmentNotFound);
			}

			var image = AttachmentService.GetThumbnail(attachment, width, height);

			using (var stream = image.OpenRead())
			{
				return File(stream.ReadFully(), attachment.FileType);
			}
		}

		[AcceptVerbs(HttpVerbs.Get), Authorize]
		public ActionResult Delete(int id, string redirect)
		{
			var attachment = AttachmentService.GetById(id);

			if (attachment == null)
			{
				return Error(Resources.Messages.AttachmentNotFound);
			}

			if (!attachment.CanDelete && !attachment.CanDeleteAny)
			{
				return NotAuthorized();
			}

			AttachmentService.Delete(attachment);

			return Redirect(redirect);
		}
	}
}